package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author: ZC0
 * @Date: 2023/02/24/16:47
 * @Description:
 */
@Component
public class RedisWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final long BEGIN_TIMESTAMP = 1672531200L;

    /**
     * 序列号位数
     */
    private static final int COUNT_BITS = 32;

    /**
     * 不同的业务生成不同的key，生成全局唯一ID
     * @param keyPrefix
     * @return
     * @date 2023-02-24 17:44
     */
    public long nextId(String keyPrefix){
        // 1. 生成时间戳
        long timeStamp = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) - BEGIN_TIMESTAMP;
        // 2. 生成序列号
        // 获取当前日期，精确到天
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + date);
        // 3. 拼接并返回
        return timeStamp << COUNT_BITS | count;
    }

}
